package com.scpii.universal.pns.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.pns.dao.DevicesDao;
import com.scpii.universal.pns.dao.PnsMessagesDao;
import com.scpii.universal.pns.dao.PnsUserMessageDevicesDao;
import com.scpii.universal.pns.dao.PnsUserMessagesDao;
import com.scpii.universal.pns.dao.UsersDao;
import com.scpii.universal.pns.dto.ClientUserDto;
import com.scpii.universal.pns.entity.PnsMessages;
import com.scpii.universal.pns.entity.PnsUserMessageDevices;
import com.scpii.universal.pns.entity.PnsUserMessages;

@Service
public class PnsMessageV2ServiceImpl extends
		PnsBaseServiceImpl<PnsMessages, Long> implements PnsMessageV2Service {
	@Resource
	private PnsMessagesDao pnsMessagesDao;

	@Resource
	private DevicesDao devicesDao;

	@Resource
	private UsersDao usersDao;

	@Resource
	private PnsUserMessagesDao pnsUserMessagesDao;

	@Resource
	private PnsUserMessageDevicesDao pnsUserMessageDevicesDao;

	@Resource
	public void setBaseDao(PnsMessagesDao pnsMessagesDao) {
		super.setBaseDao(pnsMessagesDao);
	}

	private Integer getViewCount(Long messageid) {
		String hql = "select count(id) from PnsUserMessages where messageId=:messageId and messageStatus=4";
		Map<String, Object> argsMap = new HashMap<String, Object>();
		argsMap.put("messageId", messageid);
		List<?> activeList = new ArrayList<Integer>();
		activeList = pnsUserMessagesDao.hqlGetList(hql.toString(), argsMap);
		if (activeList != null && activeList.size() == 1) {
			return Integer.parseInt(activeList.get(0).toString());
		} else {
			return 0;
		}
	}

	private Integer getSendCount(Long messageId) {
		return pnsUserMessagesDao.getSendCount(messageId);
	}

	private Integer getPushCount(Long messageId) {
		return pnsUserMessagesDao.getPushCount(messageId);
	}

	@Override
	public List<PnsMessages> getPushManageInit(Integer appId, Integer pageNo,
			Integer pageSize) {
		StringBuffer hql = new StringBuffer(" select u from PnsMessages u "
				+ "where u.appId=:appId  order by u.id desc");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appId", GenericConstants.APP_ID_PRE + appId);
		List<PnsMessages> messageList = pnsMessagesDao.findByHql(
				hql.toString(), pageNo, pageSize, map, null);
		Date date = new Date();
		if (messageList != null && messageList.size() > 0) {
			for (PnsMessages pnsMsg : messageList) {
				pnsMsg.setViewCount(getViewCount(pnsMsg.getId()));
				pnsMsg.setSendCount(getSendCount(pnsMsg.getId()));
				pnsMsg.setPushCount(getPushCount(pnsMsg.getId()));
				if (pnsMsg.getStartTime().before(date)) {
					pnsMsg.setFlag(0);
				}
				if (pnsMsg.getStartTime().after(date)) {
					pnsMsg.setFlag(1);
				}
			}
		}
		return messageList;

	}

	@Override
	public Integer getPushManageInitCount(Integer appId) {
		StringBuffer hql = new StringBuffer(
				" select count(*) from PnsMessages u " + "where u.appId=:appId");
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("appId", GenericConstants.APP_ID_PRE + appId);
		List<Long> list = pnsMessagesDao.findByHqlCount(hql.toString(), 0, 0,
				map, null);
		if (list != null && list.size() == 1) {
			return list.get(0).intValue();
		} else {
			return 0;
		}
	}

	@Override
	public void removeMessage(Long messageId) {
		pnsMessagesDao.delete(messageId);
		pnsUserMessagesDao.deleteByMessageId(messageId);
		pnsUserMessageDevicesDao.removeByMessageId(messageId);
	}

	@Override
	public void save(PnsMessages pnsMessages, Boolean allPicker,
			List<Long> ckUserBox, Integer appId, ClientUserDto condition) {
		List<Long> userIds = null;
		if (allPicker == null || allPicker == false) {
			userIds = ckUserBox;
		} else {
			List<Map<String, Object>> users = usersDao.getUserIds(
					GenericConstants.APP_ID_PRE + appId, condition);
			userIds = new ArrayList<Long>();
			for (Map<String, Object> u : users) {
				userIds.add(((BigDecimal) u.get("ID")).longValue());
			}
		}
		pnsMessages.setAppId(GenericConstants.APP_ID_PRE + appId);
		pnsMessages.setCreateTime(new Date());
		pnsMessagesDao.save(pnsMessages);
		for (Long userId : userIds) {
			PnsUserMessages pnsUserMessages = new PnsUserMessages(userId,
					pnsMessages.getId(), 1);
			pnsUserMessagesDao.save(pnsUserMessages);
			List<Map<String, Object>> divices = devicesDao
					.getByOnlineUserId(userId);
			for (Map<String, Object> device : divices) {
				PnsUserMessageDevices pnsUserMessageDevices = new PnsUserMessageDevices();
				pnsUserMessageDevices.setAppId(pnsMessages.getAppId());
				pnsUserMessageDevices.setBody(pnsMessages.getBody());
				pnsUserMessageDevices.setCreateTime(new Date());
				pnsUserMessageDevices.setDeviceId(((BigDecimal) device
						.get("ID")).longValue());
				pnsUserMessageDevices
						.setExpireTime(pnsMessages.getExpireTime());
				pnsUserMessageDevices.setIcon(pnsMessages.getIcon());
				pnsUserMessageDevices.setIosToken((String) device
						.get("IOS_TOKEN"));
				pnsUserMessageDevices.setMessageId(pnsMessages.getId());
				pnsUserMessageDevices.setMessageStatus(1);
				pnsUserMessageDevices.setStartTime(pnsMessages.getStartTime());
				pnsUserMessageDevices.setSummary(pnsMessages.getSummary());
				pnsUserMessageDevices.setTitle(pnsMessages.getTitle());
				pnsUserMessageDevices.setUserId(userId);
				pnsUserMessageDevices.setUserMessageId(pnsUserMessages.getId());
				pnsUserMessageDevicesDao.save(pnsUserMessageDevices);
			}
		}
	}

	@Override
	public void updateMessages(PnsMessages persistMessages) {
		pnsMessagesDao.update(persistMessages);
		List<PnsUserMessageDevices> messages = pnsUserMessageDevicesDao
				.getMessageByMessageId(persistMessages.getId());
		for (PnsUserMessageDevices message : messages) {
			message.setBody(persistMessages.getBody());
			message.setIcon(persistMessages.getIcon());
			message.setStartTime(persistMessages.getStartTime());
			message.setExpireTime(persistMessages.getExpireTime());
			message.setSummary(persistMessages.getSummary());
			message.setTitle(persistMessages.getTitle());
			pnsUserMessageDevicesDao.update(message);
		}
	}
}
